package com.yanggu.spark.sql

import java.util.Properties

import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession

//spark-sql读取mysql中的数据
object SparkSQL04_Load_Mysql {

  def main(args: Array[String]): Unit = {

    //1. 创建sparkConf对象
    val sparkConf = new SparkConf().setAppName("SparkSQL04_Load_Mysql").setMaster("local[*]")

    //2. 创建sparkSession对象
    val spark = SparkSession.builder().config(sparkConf).getOrCreate()

    //导入隐式转换

    //方式1: 通用读取
    spark.read.format("jdbc")
      .option("url", "jdbc:mysql://localhost:3306/yanggu")
      .option("driver", "com.mysql.jdbc.Driver")
      .option("user", "root")
      .option("password", "root")
      .option("dbtable", "user")
      .load
      .show

    //方式2:通用的load方法读取 参数另一种形式
    spark.read.format("jdbc")
      .options(Map("url" -> "jdbc:mysql://localhost:3306/yanggu",
        "driver" -> "com.mysql.jdbc.Driver", "user" -> "root", "password" -> "root",
        "dbtable" -> "user"))
      .load.show

    //方式3: JDBC的方式
    val props = new Properties()
    props.setProperty("user", "root")
    props.setProperty("password", "root")
    spark.read.jdbc("jdbc:mysql://localhost:3306/yanggu", "user", props).show
  }

}
